import * as THREE from 'three'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { ref, shallowRef } from 'vue'

// import useUnZip from '@/hooks/useJsZip'

export function useGltfModel() {
  const percentComplete = ref(0)
  const isLoading = ref(false)
  const model = shallowRef<THREE.Object3D | null>(null)

  // const { loadFile } = useUnZip()
  const onProgress = (xhr: ProgressEvent) => {
    if (xhr.lengthComputable) {
      percentComplete.value = Number(
        ((xhr.loaded / xhr.total) * 100).toFixed(0),
      )
      console.log(
        `Model loading: ${Math.round(percentComplete.value)}% complete.`,
      )
    }
  }
  const loadModel = async (glbUrl: string) => {
    return new Promise<THREE.Group>((resolve, reject) => {
      // const files = await loadFile(glbUrl)
      // const fileArr: any = []
      // for (const key in files) {
      //   if (!files[key].dir) {
      //     const blob = await files[key].async('blob')
      //     const url = URL.createObjectURL(blob)
      //     fileArr.push({
      //       name: files[key].name,
      //       url,
      //       size: blob.size,
      //     })
      //   }
      // }
      // // Load GLB Model
      const gltfLoader = new GLTFLoader()
      const dracoloader = new DRACOLoader()
      dracoloader.setDecoderPath('/draco/')
      gltfLoader.setDRACOLoader(dracoloader)

      // const gltfText = await files['21-0067釉陶钱纹罐_t2.gltf'].async('text')
      // const gltfJson = JSON.parse(gltfText)
      // gltfJson.buffers.forEach((buffer) => {
      //   const   =
      //     fileArr.find((e) => e.name === decodeURIComponent(buffer.uri))?.url ||
      //     ''
      //   console.log(uri)
      //   buffer.uri = uri
      // })
      // gltfJson.images.forEach((image) => {
      //   const uri =
      //     fileArr.find((e) => e.name === decodeURIComponent(image.uri))?.url ||
      //     ''
      //   console.log(uri)
      //   image.uri = uri
      // })
      // const modifiedGltf = new Blob([JSON.stringify(gltfJson)], {
      //   type: 'application/json',
      // })
      // const gltfUrl = URL.createObjectURL(modifiedGltf)
      isLoading.value = true
      gltfLoader.load(
        glbUrl,
        (gltf) => {
          model.value = gltf.scene
          isLoading.value = false
          resolve(gltf.scene)
        },
        onProgress,
        (error) => {
          console.error('Error loading GLB model:', error)
          reject(error)
        },
      )
    })
  }

  return {
    isLoading,
    percentComplete,
    loadModel,
  }
}
